package ying.request;/**
 * ClassName: ReqUploadDemo02
 * Package: ying.request
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/10/4 16:59
 * @Version 1.0
 */

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

@WebServlet("/req/upload02")
@MultipartConfig //上传文件
public class ReqUploadDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.利用request对象中的getParts()方法获取所有的上传文件信息
        //每个上传文件的信息对应一个Part,然后将所有的Part存储到一个集合中
        Collection<Part> uploadFiles = request.getParts();
        for (Part uploadFile : uploadFiles) {
            //获取上传文件的扩展名
            String fileName = uploadFile.getSubmittedFileName();
            String extension = fileName.substring(fileName.lastIndexOf("."));
            //拼接新的文件名,避免同名文件覆盖
            String newFileName = UUID.randomUUID() + extension;
            //先选择一个服务端的存储位置
            File dir = new File("E:/uploadFile");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //将上传的文件写入到服务端的某个位置,存储上传文件
            uploadFile.write(dir + "/" + newFileName);//直接将上传的文件写入指定位置
        }

        //上传成功后,响应上传成功提示
        String fileNames = uploadFiles.stream().map(uploadFile -> uploadFile.getSubmittedFileName()).collect(Collectors.joining(","));
        //回应中文信息时,避免乱码
        response.setContentType("text/html;charset=UTF-8");

        response.getWriter().write(fileNames + " 上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
